package com.ruoyi.quartz.thread;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.bizsys.domain.SmsTask;
import com.ruoyi.bizsys.service.ISmsTaskService;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.RspEnmu;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.quartz.mapper.QuartzSmsMapper;
import com.ruoyi.sms.domain.SmsSendData;
import com.ruoyi.sms.service.ISmsService;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.concurrent.Callable;

@Slf4j
public class SmsTaskThread implements Callable {

    private String threadName;

    private String redisName;
    private RedisCache redisCache;

    private ISmsTaskService smsTaskService;

    private ISmsService smsService;

    private QuartzSmsMapper quartzSmsMapper;

    public SmsTaskThread(String threadName, String redisName,
                         ISmsService smsService, QuartzSmsMapper quartzSmsMapper, ISmsTaskService smsTaskService, RedisCache redisCache) {
        super();
        this.threadName = threadName;
        this.redisName = redisName;
        this.redisCache = redisCache;
        this.smsService = smsService;
        this.quartzSmsMapper = quartzSmsMapper;
        this.smsTaskService = smsTaskService;
    }

    @Override
    public String toString() {
        return "SmsTaskThread [threadName=" + threadName + ", redisName=" + redisName + "]";
    }

    @Override
    public Object call() throws Exception {
        String result = ":success";
        log.info(this.threadName + "=======[START]===" + this.toString());

        List<SmsTask> smsTaskList = redisCache.getCacheList(this.redisName);
        log.info("本次有 {} 个短信记录需要执行", smsTaskList.size());
        //执行任务
//        smsTaskList.stream().forEach(p -> {
//            SmsSendData smsData = SmsSendData.builder()
//                    .smsParam(JSON.parseObject(p.getSmsParam()))
//                    .smsType(p.getSmsType())
//                    .content(p.getContent())
//                    .countryCode(p.getCountryCode())
//                    .phoneNumber(p.getPhone())
//                    .noticeType(p.getNoticeType())
//                    .build();
//            try {
//                int status = smsService.sendSms(smsData);
//                //500 发送失败
//                operationSmsTask(p.getId(), status == 500 ? 2 : 1);
//            } catch (Exception e) {
//                log.error("短信任务发送失败，手机号：{}", p.getPhone(), e);
//                operationSmsTask(p.getId(), 2);
//            }
//        });
        try {
            smsService.sendBatchSms(smsTaskList);
            operationSmsTaskList(smsTaskList, 1);
        } catch (Exception e) {
            log.error("---------批量短信任务发送失败，失败数量 ：" +smsTaskList.size() , e);
            operationSmsTaskList(smsTaskList, 2);
        }
        redisCache.deleteObject(this.redisName);

        log.info(this.threadName + "=======[END]===run result:" + result);
        return threadName + result;
    }

    /**
     * 批量修改短信任务发送状态
     * @param smsTaskList
     * @param isSend
     */
    private void operationSmsTaskList(List<SmsTask> smsTaskList, int isSend) {
        smsTaskService.updateBatchSmsTask(smsTaskList,isSend);
    }

    private int operationSmsTask(Long id, int isSend) {
        SmsTask task = new SmsTask();
        task.setId(id);
        task.setIsSend(isSend);
        return smsTaskService.updateSmsTask(task);
    }

    private boolean sendBefore(SmsTask task) {
        //用户还款日，逾期提醒插入需求：如果用户的借据当天已经跑过批量代扣，并触发了短信，则当前借据不再触发提醒还款短信
        if ("repayment".equals(task.getNoticeType())) {
            return quartzSmsMapper.withholdCountOnToday(task.getUserId()) == 0;
        }
        return true;
    }

}